# cython: language_level=3
import os
import threading
import time

import uvicorn
from dotenv import load_dotenv

from common.http import ok_response
from common.log import get_logger
from common.time import get_datetime_now
from device.app import create_device_app
from device.update_data import update_data
from device.utils.light import light_handler, read_light

load_dotenv(".env.device.light")
logger = get_logger("light_control")
GATEWAY = os.getenv("GATEWAY")
RESOURCE_ID = os.getenv("RESOURCE_ID")
OPERATOR_CODE = os.getenv("OPERATOR_CODE")
LIGHT_GPIO = os.getenv("LIGHT_GPIO")
RESOURCE_HOST = os.getenv("RESOURCE_HOST")
PORT = os.getenv("PORT")
HOST = os.getenv("HOST")


def resource_info(data_json: dict):
    return {
        "resourceId": RESOURCE_ID,
        "acquisitionTime": get_datetime_now(),
        "data": {
            "maxupCapacity": 0,
            "maxdownCapacity": 0,
            "maxupRate": 0,
            "maxdownRate": 0,
            "maxupLength": 0,
            "maxdownLength": 0,
            "controlState": 0,
            "data": data_json
        },
        "resourceName": "light",
        "resourceType": 3,
        "resourceState": "3",  # 2表示测试，3表示投运，4表示退役，5表示停机
        "maxAdjustablePower": 0,
        "assesmentMeterbox": "light",
        "listingNumber": "light",
        "RatedCapacity": 0,
        "RatedPower": 0,
        "RatedVoltage": 0,
        "Longitude": 0,
        "Latitude": 0,
        "operatorCode": OPERATOR_CODE,
        "resourceHost": RESOURCE_HOST
    }
# 也就是，运行了灯光这个main模块，程序就隔1分钟向设备轮询状态
# 持续监测灯光状态，并将状态信息定期发送到
def detect_loop():
    light_status = str(read_light(LIGHT_GPIO))
    while True:
        light_data = {
            "P": 100 if light_status == '1' else 0,
            "Q": 0,
            "Pa": 100 if light_status == '1' else 0,
            "Qa": 0,
            "Ua": 100 if light_status == '1' else 0,
            "Ia": 1 if light_status == '1' else 0,
        }
        if update_data(GATEWAY, resource_info(light_data)):
            logger.info("update data success")
        else:
            logger.error("update data failed")
        time.sleep(60)


def control_handler(payload):
    logger.info(payload)
    target_power = payload.targetPower
    light_handler(LIGHT_GPIO, int(target_power))
    return ok_response(None)


app = create_device_app(control_handler)
# 这就是启动一个后台线程来执行detect_loop函数，由于detect_loop里面sleep60秒，所以效果是每60秒轮询一次灯泡的状态
if __name__ == "__main__":
    threading.Thread(target=detect_loop, daemon=True).start()
    port = int(PORT)
    uvicorn.run(app, host=HOST, port=port)
